import re

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from itsdangerous import BadData

from meiduo_mall.settings.dev import logger
from apps.oauth.utils import SecretOauth
from utils.response_code import RETCODE
from .models import User


def generate_verify_email_url(user):
    # 1.userid email
    data_dict = {'user_id':user.id, 'email':user.email}
    # 2.加密
    secret_data = SecretOauth().dumps(data_dict)
    # 3.拼接链接
    verify_url = settings.EMAIL_ACTIVE_URL + '?token=' + secret_data
    # 4.返回链接
    return verify_url


def check_verify_email_url(token):
    try:
        token_dict = SecretOauth().loads(token)
    except BadData:
        return None
    try:
        user = User.objects.get(id=token_dict['user_id'], email=token_dict['email'])
    except Exception as e:
        logger.error(e)
        return None
    else:
        return user


def get_user_by_account(account):
    try:

        if re.match('^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    '''自定义用户认证后端'''
    def authenticate(self, request, username=None, password=None, **kwargs):
        '''重写认证方法'''
        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user


class LoginRequiredJSONMixin(LoginRequiredMixin):
    def handle_no_permission(self):
        return JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '用户未登录'})